package com.ruoyi.task.service.impl;

import com.ruoyi.task.domain.EquipmentChannelConfig;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.task.domain.ChannelConfig;
import com.ruoyi.task.domain.EquipmentCameraImportConfig;
import com.ruoyi.task.service.IChannelConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.task.mapper.EquipmentConfigMapper;
import com.ruoyi.task.domain.EquipmentConfig;
import com.ruoyi.task.service.IEquipmentConfigService;
import org.springframework.util.CollectionUtils;

/**
 * 网点摄像头配置Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-22
 */
@Service
public class EquipmentConfigServiceImpl implements IEquipmentConfigService 
{
    @Autowired
    private EquipmentConfigMapper equipmentConfigMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private IChannelConfigService channelConfigService;

    /**
     * 查询网点摄像头配置
     * 
     * @param equipmentId 网点摄像头配置主键
     * @return 网点摄像头配置
     */
    @Override
    public EquipmentConfig selectEquipmentConfigByEquipmentId(Long equipmentId)
    {
        return equipmentConfigMapper.selectEquipmentConfigByEquipmentId(equipmentId);
    }

    @Override
    public EquipmentChannelConfig selectChannelConfigByChannelId(Long channelId) {
        return equipmentConfigMapper.selectChannelConfigByChannelId(channelId);
    }

    /**
     * 查询网点摄像头配置列表
     * 
     * @param equipmentConfig 网点摄像头配置
     * @return 网点摄像头配置
     */
    @Override
    public List<EquipmentConfig> selectEquipmentConfigList(EquipmentConfig equipmentConfig)
    {
        return equipmentConfigMapper.selectEquipmentConfigList(equipmentConfig);
    }


    @Override
    public List<EquipmentChannelConfig> selectEquipmentChannelConfigList(
            EquipmentChannelConfig equipmentConfig) {
        return equipmentConfigMapper.queryEquipmentChannelConfigList(equipmentConfig);
    }

    /**
     * 新增网点摄像头配置
     * 
     * @param equipmentConfig 网点摄像头配置
     * @return 结果
     */
    @Override
    public int insertEquipmentConfig(EquipmentConfig equipmentConfig)
    {
        equipmentConfig.setCreateTime(DateUtils.getNowDate());
        SysDept sysDept = new SysDept();
        sysDept.setDeptCode(equipmentConfig.getBankCode());
        List<SysDept> sysDeptList = sysDeptMapper.selectDeptList(sysDept);
        if (!CollectionUtils.isEmpty(sysDeptList)) {
            equipmentConfig.setBankName(sysDeptList.get(0).getDeptName());
            long parentId = sysDeptList.get(0).getParentId();
            SysDept sysDeptT = new SysDept();
            sysDeptT.setDeptId(parentId);
            List<SysDept> sysDeptListParent =  sysDeptMapper.selectDeptList(sysDeptT);
            if (!CollectionUtils.isEmpty(sysDeptListParent)) {
                equipmentConfig.setSubBankCode(sysDeptListParent.get(0).getDeptCode());
                equipmentConfig.setSubBankName(sysDeptListParent.get(0).getDeptName());
            }
        }
        return equipmentConfigMapper.insertEquipmentConfig(equipmentConfig);
    }

    /**
     * 修改网点摄像头配置
     * 
     * @param equipmentConfig 网点摄像头配置
     * @return 结果
     */
    @Override
    public int updateEquipmentConfig(EquipmentConfig equipmentConfig)
    {
        equipmentConfig.setUpdateTime(DateUtils.getNowDate());
        SysDept sysDept = new SysDept();
        sysDept.setDeptCode(equipmentConfig.getBankCode());
        List<SysDept> sysDeptList = sysDeptMapper.selectDeptList(sysDept);
        if (!CollectionUtils.isEmpty(sysDeptList)) {
            equipmentConfig.setBankName(sysDeptList.get(0).getDeptName());
            long parentId = sysDeptList.get(0).getParentId();
            SysDept sysDeptT = new SysDept();
            sysDeptT.setDeptId(parentId);
            List<SysDept> sysDeptListParent =  sysDeptMapper.selectDeptList(sysDeptT);
            if (!CollectionUtils.isEmpty(sysDeptListParent)) {
                equipmentConfig.setSubBankCode(sysDeptListParent.get(0).getDeptCode());
                equipmentConfig.setSubBankName(sysDeptListParent.get(0).getDeptName());
            }
        }
        return equipmentConfigMapper.updateEquipmentConfig(equipmentConfig);
    }

    /**
     * 批量删除网点摄像头配置
     * 
     * @param equipmentIds 需要删除的网点摄像头配置主键
     * @return 结果
     */
    @Override
    public int deleteEquipmentConfigByEquipmentIds(Long[] equipmentIds)
    {
        return equipmentConfigMapper.deleteEquipmentConfigByEquipmentIds(equipmentIds);
    }

    /**
     * 删除网点摄像头配置信息
     * 
     * @param equipmentId 网点摄像头配置主键
     * @return 结果
     */
    @Override
    public int deleteEquipmentConfigByEquipmentId(Long equipmentId)
    {
        return equipmentConfigMapper.deleteEquipmentConfigByEquipmentId(equipmentId);
    }

    @Override
    public boolean importEquipmentCameraImportConfig(List<EquipmentCameraImportConfig> equipmentCameraConfigs, String createBy) {
        if (CollectionUtils.isEmpty(equipmentCameraConfigs)) {
            throw new BaseException("导入数据为空!");
        }
        //检查分行和网点是否已存在
        List<String> errorList = new ArrayList<>();
        AtomicInteger counter = new AtomicInteger(2);
        equipmentCameraConfigs.forEach(equipmentCameraConfig -> {
            StringBuilder errorMsg = new StringBuilder();
            String bankCode = equipmentCameraConfig.getBankCode();
            String channel = equipmentCameraConfig.getEquipmentChannel();
            String equipmentIp = equipmentCameraConfig.getEquipmentIp().trim();

            SysDept sysDept = new SysDept();
            sysDept.setDeptCode(bankCode);
            List<SysDept> sysDeptList = sysDeptMapper.selectDeptList(sysDept);

            if (CollectionUtils.isEmpty(sysDeptList)) {
                errorMsg.append("网点编码").append(bankCode).append("未配置！;");
            }
            try {
                Integer.parseInt(channel);
            }  catch (NumberFormatException e) {
                errorMsg.append("摄像机通道号").append(channel).append("应为数字(1-64)范围！");
            }
            if (StringUtils.isNotEmpty(equipmentIp)) {
                if (!isValidIPv4Regex(equipmentIp)){
                    errorMsg.append("录像机IP").append(equipmentIp).append("不合法！");
                };
            } else {
                errorMsg.append("录像机IP").append(equipmentIp).append("不能为空！");
            }
            int row = counter.getAndIncrement();
            if (StringUtils.isNotEmpty(errorMsg)) {
                errorList.add("第" + row  + "行错误：" + errorMsg + "\n");
            }
        });
        if (!CollectionUtils.isEmpty(errorList)) {
            throw new BaseException(errorList.toString());
        }
        //执行操作
        equipmentCameraConfigs.forEach(equipmentCameraConfig -> {
            String bankCode = equipmentCameraConfig.getBankCode();
            String equipmentPwd = equipmentCameraConfig.getEquipmentPwd();
            String equipmentUser = equipmentCameraConfig.getEquipmentUser();
            String equipmentName = equipmentCameraConfig.getEquipmentName();
            String channel = equipmentCameraConfig.getEquipmentChannel();
            String equipmentChannelName = equipmentCameraConfig.getEquipmentChannelName();
            String cameraComputerIp = equipmentCameraConfig.getCameraComputerIp();

            SysDept dept = new SysDept();
            dept.setDeptCode(bankCode);
            List<SysDept> sysDeptList = sysDeptMapper.selectDeptList(dept);
            String equipmentIp = equipmentCameraConfig.getEquipmentIp().trim();

            EquipmentConfig equipmentConfig = new EquipmentConfig();
            equipmentConfig.setBankCode(bankCode);
            equipmentConfig.setEquipmentIp(equipmentIp);

            //添加设备或者更新录像机设备
            long equipmentId;
            List<EquipmentConfig> equipmentConfigList = equipmentConfigMapper.selectEquipmentConfigList(equipmentConfig);
            if (!CollectionUtils.isEmpty(equipmentConfigList)) {
                EquipmentConfig equipmentConfigT = equipmentConfigList.get(0);
                equipmentId = equipmentConfigT.getEquipmentId();
                equipmentConfigT.setEquipmentPwd(equipmentPwd);
                equipmentConfigT.setEquipmentUser(equipmentUser);
                equipmentConfigT.setRemark(equipmentName);
                equipmentConfigT.setStatus("0");
                equipmentConfigT.setEquipmentType("01");
                equipmentConfigT.setEquipmentPort("37777");
                equipmentConfigMapper.updateEquipmentConfig(equipmentConfigT);
            }  else {
                equipmentConfig.setBankName(sysDeptList.get(0).getDeptName());
                equipmentConfig.setEquipmentPwd(equipmentPwd);
                equipmentConfig.setEquipmentUser(equipmentUser);
                equipmentConfig.setRemark(equipmentName);
                equipmentConfig.setStatus("0");
                equipmentConfig.setEquipmentPort("37777");
                equipmentConfig.setEquipmentType("01");
                this.insertEquipmentConfig(equipmentConfig);
                equipmentId = equipmentConfig.getEquipmentId();
            }


            //处理摄像头数据
            ChannelConfig channelConfig = new ChannelConfig();
            channelConfig.setEquipmentId(equipmentId);
            channelConfig.setEquipmentChannel(channel);
            List<ChannelConfig> channelConfigList = channelConfigService.selectChannelConfigList(channelConfig);
            if (!CollectionUtils.isEmpty(channelConfigList)) {
                ChannelConfig channelConfigT= channelConfigList.get(0);
                channelConfigT.setRemark(equipmentChannelName);
                channelConfigT.setCameraComputerIp(cameraComputerIp);
                channelConfigT.setStatus("0");
                channelConfigService.updateChannelConfig(channelConfigT);
            } else {
                channelConfig.setRemark(equipmentChannelName);
                channelConfig.setStatus("0");
                channelConfig.setCameraComputerIp(cameraComputerIp);
                channelConfigService.insertChannelConfig(channelConfig);
            }
        });
        return true;
    }

    private static boolean isValidIPv4Regex(String ipAddress) {
        if (ipAddress == null || ipAddress.isEmpty()) {
            return false;
        }
        String ipRegex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." +
                "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +
                "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +
                "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";

        Pattern pattern = Pattern.compile(ipRegex);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }
}
